package graphic;




/**
 * @author SASHA
 *
 */

import java.awt.Graphics;

import java.awt.Point;

import javax.swing.JComponent;
import graphic.SingleCar;
import Graph.Graph;
import Graph.optimalWay;
import Graph.pathway;

public class AllCars extends JComponent {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static Graph City;
	public int graph[][] = new int [1000][1000];
	public static int number;

	public static SingleCar car;
	public static int CarsNow = 0;
	public static int maxCars = 100;
	public static int CarsFlags [] = new int [1000];
	public static SingleCar [] CarsArray = new SingleCar [1000];
	public int length;
	public Point point [];
	public static optimalWay rMap;
	public pathway rWay;
	private static int i;
	
	@SuppressWarnings("static-access")
	public AllCars(Graph City){
		this.City = City;
		point = City.getPoint();
		graph = City.getGraph();
		number = City.getNumber();
		rMap = new optimalWay (City);
		for(int i = 0; i < 1000; i++){
			CarsFlags[i] = -1;
		}
	}
	
	
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		clean();
		paintAllCars(g);
	}
	
	public static int addCar(pathway oWay){
		
		if (CarsNow >= maxCars) return -1;
		for(i = 0; i < maxCars; i++){
			if(CarsFlags[i] == -1){
				++CarsNow;
				CarsFlags[i] = 1;
				CarsArray[i] = new SingleCar(City, oWay);
				return i;
			}
		}
		return -1;
	}
	
	public int deleteCar(int id){
		if(CarsFlags[id] == 0){
			if(CarsArray[id] == null) return -1;
			--CarsNow;
			CarsArray[id] = null;
			CarsFlags[id] = -1;
			return 1;
		} else return -1;
	}
	
	public void clean(){
		for (i = 0; i < 1000; i++){
			if(CarsArray[i] == null) continue;
			if (CarsFlags[i] == 1) {
				if(CarsArray[i].getFlagDeleted() == 1){
					CarsFlags[i] = 0;
					deleteCar(i);
				}
			}
		}
	}
	
	public void paintAllCars(Graphics g){
		for(i = 0; i < 1000; i++) {
			if(CarsArray[i] == null) continue;
			if(CarsFlags[i] == 1) CarsArray[i].paintCar(g);
		}
	}
	public static int addRandomCar(){
		int start = (int) Math.round(Math.random() * ((double) number));
		int finish = (int) Math.round(Math.random() * ((double) number));
		if(CarsNow >= maxCars) return -1;
		else {
			int k = 0;
			while (k < 1000 && (optimalWay.length_matrix[start][finish] >= City.getNoRoad() || start >= number || finish >= number || start < 0 || finish < 0)){
				++k;
				if(start >= Graph.maxVertexes || finish >= Graph.maxVertexes) continue;
				start = (int) Math.round(Math.random() * ((double) number));
				finish = (int) Math.round(Math.random() * ((double) number));
			}
			pathway randomWay = new pathway();
			randomWay = rMap.getCourse(City, start, finish);
			addCar(randomWay);
			return 1;
		}
	}
	public void setFlagZero(int id){
		CarsFlags[id] = 0;
	}

	public void setmaxCars(int maxCars2) {
		maxCars = maxCars2;
	}
}
